#include<iostream>
#include<fstream>
#include "contacts.pb.h" 
#include "contacts.pb.cc" 

using namespace std ; 
using namespace contacts ;




void PrintContacts(const Contacts& contacts) 
{
    //contacts.contacts_size() 的含义 ？  ——>  repetead类型数组的长度
    for(int i = 0 ; i < contacts.contacts_size(); i++)
    {
        //引用，避免拷贝 ; 
        const PeopleInfo& people = contacts.contacts(i);
        cout << "----------Contact Person " << i + 1 << "-----------" << endl ;
        cout << "name :" << people.name() <<endl;
        cout << "age  :" << people.age() << endl ; 
        int j = 1 ; 
        
        // 范围for ？ ？ ？ ？ ？ ？ ？ 
        for(const PeopleInfo_Phone& phone : people.phone())
        {
            cout << "phone" << j++ << " : " << phone.number() << endl ;
            cout << "phone type :" <<  phone.TypePhone_Name(phone.type()) << endl ; 
            //  phone.TypePhone_Name() 是解析枚举数字对应的类型————枚举字段名称
            //  phone.type()返回该phone的 type枚举类型中的枚举对应数字 （这里字段名取的不好 枚举字段名为type） 
        }


        /*   import Any 库后可用

        if (people.has_data() && people.data().Is<Address>()) 
        {
            Address address;
            people.data().UnpackTo(&address);
            if (!address.home_address().empty()) 
            {
                cout << "家庭地址：" << address.home_address() << endl;
            } 
            if (!address.unit_address().empty()) 
            {
            cout << "单位地址：" << address.unit_address() << endl;
            } 
         }

        */

       // 使用 people.has_qq() 方法 入股qq被设置则会返回1 ； 
       //switch 写法扩展性好，但是比较难记住
       switch (people.other_contact_case())
       {
       case PeopleInfo::OtherContactCase::kQq: // ! ! !
        cout << "QQ :" << people.qq() << endl; 
        break;
        
        case PeopleInfo::OtherContactCase::kWeixin:
        cout << "WeChat :" << people.weixin() << endl ; 
        break;
       
        case PeopleInfo::OtherContactCase::OTHER_CONTACT_NOT_SET:
        break;

        default : 
        break;
       }

       

    }
}



int main (int argc, char*argv[])
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    if (argc != 2) 
    {
        cerr << "Usage: " << argv[0] << "CONTACTS_FILE" << endl;
        return -1;
    }    

    //二进制读取 contacts 
    Contacts contacts ;
    fstream input(argv[1], ios::in | ios::binary);
    if(!contacts.ParseFromIstream(&input))
    {
        cerr << "failed Parse " << endl ;
        input.close();
        return -1 ;
    }

    //打印 
    PrintContacts(contacts);

    input.close();
    google::protobuf::ShutdownProtobufLibrary();
    return 0 ; 

}

// 编译指令:
// g++ -o read read.cpp -std=c++11 -lprotobuf -pthread
// 删除指令：
// rm -f read
// 执行指令：
// ./read contacts.bin 